package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**病历信息-停用
 * @author Administrator
 *
 */
public class MedicalRecordActivity extends Activity {

	private TextView title, hs, ks, bh, record_change_percentage, ch, zyh, xm,
			fb, nl, ryrq, bq;
	private ListView record_list_view;
	private LinearLayout items, myContent;
	private MyViewGroup myViewGroup;
	public static final LayoutParams FULL = new LayoutParams(
			LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	public static final LayoutParams DEFINDELP = new LayoutParams(100,
			LayoutParams.FILL_PARENT);
	public static final LayoutParams TEXTLP = new LayoutParams(200, 50);
	public static final int TEXTSIZE = 20;
	public static final String[] TITLES = new String[] { "门诊诊断", "入院情况",
			"入院诊断", "出院诊断" };
	private List<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
	CustomProgressDialog proDialog;// 加载框
	MedicalRecordActivity oThis = this;
	MyAdapter myAdapter;// listview
	private List<String> key = new ArrayList<String>();
	private Map<String, String> maps = new HashMap<String, String>();
	private String[] s = { "ryzd", "mzzd", "ryqk", "cyqk" };
	private String[] ss = { "入院诊断", "门诊诊断", "入院情况", "出院情况" };
	JSONObject obj = null;
	MyApplication myApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.medical_record);
		setTitle("病历查询");
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		findViews();
		proDialog = CustomProgressDialog.createDialog(this);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();
	}

	private void initTitle() {
		TextView tv = null;
		myViewGroup = new MyViewGroup(oThis);
		for (int i = 0; i < TITLES.length; i++) {
			tv = new TextView(this);
			tv.setText(TITLES[i] + "　");
			tv.setTextSize(TEXTSIZE);
			tv.setTextColor(Color.BLACK);
			tv.setBackgroundColor(getResources().getColor(R.color.color_pink));
			myViewGroup.addView(tv);
		}
		items.addView(myViewGroup);
	}

	private void initData() {
		try {
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid",
					myApplication.getAccount() == null ? "" : myApplication
							.getAccount()));
			ls.add(new BasicNameValuePair("syxh",
					myApplication.getAccount() == null ? "" : myApplication
							.getSyxh()));
			// ls.add(new BasicNameValuePair("userid", "huaifeng"));
			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOST + URLUtils.URLRECORD, ls);
			Map<String, Object> map;
			if (json != null) {
				if (!json.toString().equals(
						"{\"msg\":\"系统错误！\",\"success\":\"false\"}")) {

					if (json.getJSONArray("blinfo").length() > 0) {
						obj = json.getJSONArray("blinfo").getJSONObject(0);
						if (obj.length() > 0) {
							for (int i = 0; i < s.length; i++) {
								maps.put(s[i].toString(), ss[i].toString());
							}
							for (int i = 0; i < obj.names().length(); i++) {
								map = new HashMap<String, Object>();
								String str = obj.names().get(i).toString();
								map.put(str, obj.get(str).toString());
								for (int j = 0; j < s.length; j++) {
									if (str.equals(s[j])) {
										key.add(str);
										listItem.add(map);
									}
								}
							}
							bundle.putInt("type", 0);

						}
					} else {
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				} else {
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}
			} else {
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void findViews() {
		// title = (TextView) findViewById(R.id.title);
		hs = (TextView) findViewById(R.id.hs);
		ks = (TextView) findViewById(R.id.ks);
		bh = (TextView) findViewById(R.id.bh);
		ch = (TextView) findViewById(R.id.ch);
		zyh = (TextView) findViewById(R.id.zyh);
		xm = (TextView) findViewById(R.id.xm);
		fb = (TextView) findViewById(R.id.fb);
		nl = (TextView) findViewById(R.id.nl);
		ryrq = (TextView) findViewById(R.id.ryrq);
		bq = (TextView) findViewById(R.id.bq);
		record_list_view = (ListView) findViewById(R.id.record_list_view);
		// items = (LinearLayout) findViewById(R.id.items);
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				int type = msg.getData().getInt("type");
				switch (type) {
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, msg.getData().getString("msg"),
							Toast.LENGTH_SHORT).show();
					break;
				case 0:
					proDialog.dismiss();
					hs.setText("床位医生:" + obj.getString("cwysmc"));
					ks.setText("科室:" + obj.getString("ksmc"));
					bh.setText("病区:" + obj.getString("bqmc"));
					ch.setText(obj.getString("ch"));
					zyh.setText(obj.getString("zyh"));
					xm.setText(obj.getString("hzxm"));
					fb.setText("自费");
					nl.setText(obj.getString("age"));
					ryrq.setText(obj.getString("ryrq").substring(0, 4) + "-"
							+ obj.getString("ryrq").substring(4, 6) + "-"
							+ obj.getString("ryrq").substring(6, 8));
					bq.setText("一般");
					myAdapter = new MyAdapter();
					record_list_view.setAdapter(myAdapter);
					record_list_view
							.setOnItemClickListener(new OnItemClickListener() {

								public void onItemClick(
										AdapterView<?> adapterview, View view,
										int position, long id) {
									// TODO Auto-generated method stub
									HashMap<String, String> map = (HashMap<String, String>) adapterview
											.getItemAtPosition(position);
									// 无须显示
									// Toast.makeText(oThis,
									// map.get(key.get(position)),
									// Toast.LENGTH_SHORT).show();
								}
							});
					break;

				default:
					break;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		};
	};

	/**
	 * 单开一个子线程后台读取数据，成功后通知UI更新
	 * 
	 * @author zjj
	 * 
	 */
	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			initData();
			Looper.loop();
		}

	}

	/**
	 * 自定义textView自动换行 实现标签效果
	 * 
	 * @author zjj
	 * 
	 */
	class MyViewGroup extends ViewGroup {
		private final static String TAG = "MyViewGroup";

		private final static int VIEW_MARGIN = 2;

		public MyViewGroup(Context context) {
			super(context);
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			Log.d(TAG, "widthMeasureSpec = " + widthMeasureSpec
					+ " heightMeasureSpec" + heightMeasureSpec);

			for (int index = 0; index < getChildCount(); index++) {
				final View child = getChildAt(index);
				// measure
				child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			}

			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}

		@Override
		protected void onLayout(boolean arg0, int arg1, int arg2, int arg3,
				int arg4) {
			Log.d(TAG, "changed = " + arg0 + " left = " + arg1 + " top = "
					+ arg2 + " right = " + arg3 + " botom = " + arg4);
			final int count = getChildCount();
			int row = 0;// which row lay you view relative to parent
			int lengthX = arg1; // right position of child relative to parent
			int lengthY = arg2; // bottom position of child relative to parent
			for (int i = 0; i < count; i++) {

				final View child = this.getChildAt(i);
				int width = child.getMeasuredWidth();
				int height = child.getMeasuredHeight();
				lengthX += width + VIEW_MARGIN;
				lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height
						+ arg2;
				// if it can""t drawing on a same line ， skip to next line
				if (lengthX > arg3) {
					lengthX = width + VIEW_MARGIN + arg1;
					row++;
					lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN
							+ height + arg2;

				}

				child.layout(lengthX - width, lengthY - height, lengthX,
						lengthY);
			}

		}

	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 * 
	 */
	class MyAdapter extends BaseAdapter {

		TextView tv = null;
		MyViewGroup group = null;

		public int getCount() {
			// TODO Auto-generated method stub
			return listItem.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listItem.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(
					R.layout.recore_list, null);
			String temp = key.get(position);
			record_change_percentage = (TextView) view
					.findViewById(R.id.record_change_percentage);
			record_change_percentage.setText(maps.get(temp));
			record_change_percentage.setTextSize(18);
			record_change_percentage.setTextColor(Color.BLACK);
			myContent = (LinearLayout) view.findViewById(R.id.myContent);
			tv = new TextView(oThis);
			// group = new MyViewGroup(oThis);
			tv.setText(map.get(temp).toString());
			tv.setTextSize(18);
			tv.setTextColor(Color.BLACK);
			myContent.addView(tv);
			// if (position % 2 != 0) {
			// view.setBackgroundDrawable(getResources().getDrawable(
			// R.drawable.gridoddbg));
			// } else {
			// view.setBackgroundDrawable(getResources().getDrawable(
			// R.drawable.gridoddbg));
			// }
			return view;
		}

	}

}
